<template>
  <div class="main">
    <!-- <van-sticky class="van-sticky"> -->
    <!--    {{userInfo.avatar}}-->
    <div class="nav">
      <img :src="back" alt="" @click="handleBack" />
      <div>个人信息</div>
    </div>
    <div class="tx">
      <!-- <van-image class="avatar" @click="changeImg()"
                 :src="userInfo.avatar ? store.state.imgUrl+ userInfo.avatar : logo" round
      /> -->
      <div
        class="avatar"
        @click="changeImg()"
        :style="{
          backgroundImage: `url(${
            userInfo.avatar ? store.state.imgUrl + userInfo.avatar : logo
          })`,
        }"
      >
        <van-loading v-show="uploadStatus" size="24px" type="spinner"
          >上传中...</van-loading
        >
        <!-- <span style="">上传中...</span> -->
      </div>
      <div class="tip">点击更换头像</div>
      <!-- <div  class="avatar" @click="changeImg()"
           :style="{backgroundImage: `url(${ userInfo.avatar ? store.state.imgUrl + userInfo.avatar : logo})`}">
      </div> -->
      <!-- <div v-if="isUrl" class="avatar" @click="changeImg()"
           :style="{backgroundImage: `url(${userInfo.avatar ? userInfo.avatar : logo})`}">
   
      </div> -->

      <!--       <img :src="getImg(userInfo.avatar)"/>-->
      <!-- <img v-else :src="logo" @click="changeImg()" class="avatar"/> -->
      <!-- <div>点击更换头像</div> -->
      <!--      <div v-else class="avatar"-->
      <!--           :style="{backgroundImage: `${userInfo.avatar?userInfo.avatar:logo})`}">-->
      <!--      </div>-->
    </div>
    <!--    <van-uploader-->
    <!--        v-model="fileList"-->
    <!--        accept="image/*"-->
    <!--        multiple-->
    <!--        :max-count="1"-->
    <!--        capture="camera"-->
    <!--        :max-size="500 * 1024"-->
    <!--        @oversize="handleOversize"-->
    <!--        @before-delete="handleBeforeDelete"-->
    <!--        @after-read="handleAfterRead"-->
    <!--    >-->
    <!--    <div class="change-avatar" @click="changeImg()">-->
    <!--      点击更换头像-->
    <!--    </div>-->
    <!--    </van-uploader>-->
    <!-- </van-sticky> -->
    <div class="body">
      <van-form ref="form">
        <!-- <van-field
        v-model.trim="userInfo.mobile"
        name="手机号码"
        label="新手机号"
        placeholder="请输入手机号码"
        clearable
        :rules="[{ pattern }]"></van-field> -->
        <van-field
          v-model="userInfo.nickname"
          label="昵称"
          placeholder="请输入昵称"
          input-align="right"
          maxlength="6"
        />
        <van-field
          v-model="userInfo.name"
          label="姓名"
          placeholder="请输入姓名"
          input-align="right"
          maxlength="6"
        />
        <van-cell
          title="性别"
          is-link
          :value="userInfo.sexName ? userInfo.sexName : '点击选择性别'"
          @click="showSex = true"
        />
        <van-cell
          title="出生日期"
          is-link
          :value="userInfo.birthday ? userInfo.birthday : '点击选择出生日期'"
          @click="showDatePicker = true"
        />
        <van-cell
          title="年龄"
          :value="String(userInfo.age) ? userInfo.age + '岁' : '请选择出生日期'"
        />
        <van-field
          v-model="userInfo.height"
          label="身高"
          placeholder="请输入身高"
          input-align="right"
          type="digit"
          maxlength="3"
        >
          <template #extra>
            <span class="unit">CM</span>
          </template>
        </van-field>
        <van-field
          v-model.trim="userInfo.weight"
          label="体重"
          name="体重"
          placeholder="请输入体重"
          input-align="right"
          type="number"
          autocomplete="off"
          :rules="[{ validator: weightP }]"
        >
          <template #extra>
            <span class="unit">KG</span>
          </template>
        </van-field>
        <van-cell title="BMI" :value="userInfo.bmi ? userInfo.bmi : '0.0'" />
        <van-cell
          title="吸烟"
          is-link
          :value="userInfo.smokingName"
          @click="showSmoking = true"
        />
        <!-- <div class="footer">
          <div class="size" @click="commit">提交</div>
          <van-button class="size" round block type="info" @click="commit" native-type="submit">提交</van-button>
        </div> -->
        <div class="footer">
          <van-button class="size" @click="commit">确 认</van-button>
        </div>
      </van-form>
    </div>
    <van-action-sheet
      v-model="showSex"
      :actions="sexActions"
      cancel-text="取消"
      @select="onSelect"
    />
    <van-action-sheet
      v-model="showSmoking"
      :actions="smokingActions"
      cancel-text="取消"
      @select="onSelectSmoking"
    />
    <van-popup v-model="showDatePicker" position="bottom">
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="getDateTime"
        @cancel="showDatePicker = false"
      />
    </van-popup>
  </div>
</template>

<script>
import { editUserInfo, getGenderList, getSmokingList } from "../../../api/my";
import { dateFormat } from "@/utils/date.js";
import store from "@/store";

export default {
  name: "personInfo",
  data() {
    return {
      uploadStatus: false,
      coverUrl: "",
      coverFile: "",
      // logo: require("@/assets/threeImage.png"),
      label: "体重",
      showSmoking: false,
      smokingActions: [],
      showSex: false,
      sexActions: [],
      showDatePicker: false,
      currentDate: new Date(),
      minDate: new Date(1880, 0, 1),
      maxDate: new Date(),
      back: require("@/assets/my/back.png"),
      setImg: require("@/assets/my/set-icon.png"),
      userInfo: {
        avatar: "",
        nickName: "", //昵称
        name: "", //姓名
        sex: "", //0男 1女 2未知
        sexName: "",
        birthday: "", //生日
        age: "",
        height: "",
        weight: "",
        bmi: "", //BMI = 体重（千克） / (身高（米） × 身高（米）)
        isSmoking: "", // 0频繁 1偶尔 3不抽烟
        smokingName: "",
      },
      isUrl: true,
      store: store,
      // weightP:/^[0-9]+(\.[0-9]{1,2})?$/,
      pattern: /^[1][3,4,5,6,7,8,9][0-9]{9}$/,
    };
  },
  created() {},
  watch: {
    "userInfo.weight": {
      handler(newVal, oldVal) {
        console.log("监听到数据变化");
        this.calculateBMI();
      },
      deep: true,
    },
    "userInfo.height": {
      handler(newVal, oldVal) {
        console.log("监听到数据变化");
        this.calculateBMI();
      },
      deep: true,
    },
  },
  async mounted() {
    window["getInfoFromFlutter"] = (info) => {
      if (JSON.parse(info).action === "upload") {
        // this.$toast(info)
        this.getInfoFromFlutter(info);
      }
    };
    this.userInfo = this.$route.query.obj;
    // this.userInfo = this.$store.state.userInfo
    console.log("用户信息：", this.userInfo);
    console.log("userInfo", this.userInfo);
    this.userInfo.age = this.userInfo.birthday
      ? this.getBrithAge(new Date(this.userInfo.birthday))
      : "";
    if (this.userInfo.avatar) {
      if (this.userInfo.avatar.indexOf("http") != -1) {
        this.isUrl = true;
      } else {
        this.isUrl = false;
      }
    }
    let smokings = await this.getSmoking(); // 吸烟
    smokings.forEach((item, index) => {
      let obj = {
        name: item.label,
        value: item.value,
      };
      this.smokingActions.push(obj);
    });
    let sexs = await this.getSex(); //性别
    sexs.forEach((item, index) => {
      let obj = {
        name: item.label,
        value: item.value,
      };
      this.sexActions.push(obj);
    });
    this.sexActions.map((item, index) => {
      if (item.value == this.userInfo.sex) {
        this.userInfo.sexName = item.name;
      }
    });
    this.smokingActions.map((item, index) => {
      if (item.value == this.userInfo.isSmoking) {
        this.userInfo.smokingName = item.name;
      }
    });
  },
  methods: {
    imgUrlToFile(url) {
      var self = this;
      var imgLink = url;
      var tempImage = new Image();
      //如果图片url是网络url，要加下一句代码
      tempImage.crossOrigin = "*";
      tempImage.onload = function () {
        var base64 = self.getBase64Image(tempImage);
        var imgblob = self.base64toBlob(base64);
        var filename = self.getFileName(self.ruleForm.coverUrl);
        self.ruleForm.coverFile = self.blobToFile(imgblob, filename);
      };
      tempImage.src = imgLink;
    },
    getBase64Image(img) {
      var canvas = document.createElement("canvas");
      canvas.width = img.width;
      canvas.height = img.height;
      var ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0, img.width, img.height);
      var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
      var dataURL = canvas.toDataURL("image/" + ext);
      return dataURL;
    },
    base64toBlob(base64) {
      let arr = base64.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
    blobToFile(blob, filename) {
      // edge浏览器不支持new File对象，所以用以下方法兼容
      blob.lastModifiedDate = new Date();
      blob.name = filename;
      return blob;
    },
    getFileName(url) {
      // 获取到文件名
      let pos = url.lastIndexOf("/"); // 查找最后一个/的位置
      return url.substring(pos + 1); // 截取最后一个/位置到字符长度，也就是截取文件名
    },
    handleFocus() {
      this.placeholder = "请输入身高";
    },
    handleBlur() {
      this.placeholder = "请输入身高";
    },
    // handleBeforeDelete() {
    //   // 删除文件前的处理逻辑
    //   this.avatarUrl = '';
    // },
    // handleAfterRead(file) {
    //   // 读取文件后的处理逻辑
    //   this.avatarUrl = URL.createObjectURL(file.file);
    // },
    // handleOversize(){
    //   this.$toast('文件大小不能超过 500kb');
    // },
    getSex() {
      return new Promise((resolve, reject) => {
        getGenderList().then((res) => {
          resolve(res.data);
        });
      });
    },
    getSmoking() {
      return new Promise((resolve, reject) => {
        getSmokingList().then((res) => {
          resolve(res.data);
        });
      });
    },
    getDateTime() {
      this.userInfo.birthday = dateFormat(
        new Date(this.currentDate),
        "yyyy-MM-dd"
      );
      // console.log(new Date(this.currentDate))
      this.userInfo.age = this.getBrithAge(new Date(this.currentDate));
      console.log(this.userInfo.age);
      this.showDatePicker = false;
    },
    calculateBMI() {
      console.log("calc");
      if (this.userInfo.height && this.userInfo.weight) {
        const heightInMeter = this.userInfo.height / 100; // 将身高从cm转换为m
        const bmi = this.userInfo.weight / (heightInMeter * heightInMeter); // 计算BMI
        this.userInfo.bmi = bmi.toFixed(2); // 保留两位小数
      }
    },
    getBrithAge(birthday) {
      var nowDay = new Date();
      //出生年月日
      var birthYear = birthday.getFullYear();
      var birthMonth = birthday.getMonth() + 1;
      var birthDate = birthday.getDate();
      //当前年月日
      var nowYear = nowDay.getFullYear();
      var nowMonth = nowDay.getMonth() + 1;
      var nowDate = nowDay.getDate();

      //计算年差
      var age = nowYear - birthYear;
      //当前月大于出生月，则岁数不足
      if (nowMonth < birthMonth) {
        age = age - 1;
      } else if (nowMonth == birthMonth) {
        if (nowDate < birthDate) {
          age = age - 1;
        }
      }
      return age;
    },
    onSelect(item) {
      this.userInfo.sexName = item.name;
      this.userInfo.sex = item.value;
      this.showSex = false;
    },
    onSelectSmoking(item) {
      this.userInfo.smokingName = item.name;
      this.userInfo.isSmoking = item.value;
      this.showSmoking = false;
    },
    commit() {
      const userInfo = {
        avatar: this.userInfo.avatar,
        nickname: this.userInfo.nickname,
        name: this.userInfo.name,
        sex: this.userInfo.sex,
        birthday: this.userInfo.birthday,
        age: this.userInfo.age,
        height: this.userInfo.height,
        weight: this.userInfo.weight,
        isSmoking: this.userInfo.isSmoking,
        // password:this.userInfo.password
      };
      if (this.userInfo.nickname) {
        if (this.weightP(String(this.userInfo.weight))) {
          // console.log(this.userInfo)
          editUserInfo(userInfo).then((res) => {
            this.$toast.success("修改成功");
            this.$router.push({ path: "/my" });
            let message = {
              action: "showBottom",
              param: {},
            };
            getInfoFromVue.postMessage(JSON.stringify(message));
            let message1 = {
              action: "changedAvatar",
              param: this.userInfo.avatar,
            };
            getInfoFromVue.postMessage(JSON.stringify(message1));
          });
        } else {
          this.$toast("体重请保留两位小数");
        }
      } else {
        this.$toast("昵称不能为空");
      }
    },
    // 体重校验
    weightP(v) {
      if (v) {
        return /^[0-9]+(\.[0-9]{1,2})?$/.test(v);
      } else {
        return /\s/;
      }
    },
    handleBack() {
      this.$router.go(-1);
      let message = {
        action: "showBottom",
        param: {},
      };
      getInfoFromVue.postMessage(JSON.stringify(message));
    },
    handleUploadPic(file) {
      // 上传完成后执行的回调函数，可以用来处理上传成功后的逻辑，如上传到服务器等。
      if (file.type === "image/jpeg" || file.type === "image/png") {
        const formData = new FormData();
        formData.append("file", file.file);
        axios
          .post("/api/upload", formData)
          .then((response) => {
            this.$toast.success("上传成功");
            // this.fileList.push({ ...file, url: response.data.url }); // 将上传成功的文件添加到文件列表中，并设置文件的URL为返回的URL。
          })
          .catch((error) => {
            this.$toast.fail("上传失败");
            // console.error(error);
          });
      } else {
        this.$toas.fail("只支持上传 JPG/PNG 格式的图片");
      }
    },

    changeImg() {
      let message = {
        action: "upload",
        param: {
          type: "image", //必填
          callback: 1,
        },
      };
      let _urlObj = {};
      getInfoFromVue.postMessage(JSON.stringify(message));
      // this.handleUploadPic(_file)
      this.imgUrlToFile();
    },
    getInfoFromFlutter(info) {
      let data = JSON.parse(info);
      if (data.param.type == "image") {
        if (data.param.images && data.param.images.length > 0) {
          // this.imageList = data.param.images;
          this.userInfo.avatar = data.param.images[0];
          //修改store中的userInfo中的avater
          this.$store.dispatch("updateAvatar", this.userInfo.avatar);
        }
      }
    },
  },
};
</script>

<style scoped lang="less">
.main {
  height: 100vh;
  padding: 0px 15px;

  .unit {
    float: right;
    margin-left: 4px;
    color: #999;
  }

  .nav {
    height: 44px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 20px;
    font-weight: 500;

    > img {
      width: 10px;
      height: 16px;
      position: absolute;
      left: 15px;
    }
  }

  .tx {
    display: flex;
    justify-content: center;
    padding-top: 14px;
    flex-direction: column;
    align-items: center;

    .tip {
      font-size: 15px;
      color: #ccc;
    }

    .avatar {
      background-repeat: no-repeat;
      background-size: 100%;
      width: 89px;
      height: 89px;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      //background: rgba(0, 0, 0, 0.8);
      opacity: 1;
      background-repeat: no-repeat;
      background-position: center;
      background-size: cover;

      > img {
        width: 41px;
        height: 41px;
      }
    }
  }

  .change-avatar {
    font-size: 15px;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 17.38px;
    color: rgba(84, 84, 84, 1);
    text-align: center;
    margin-top: 5px;
  }

  .body {
    /deep/ .van-cell__title {
      font-size: 17px;
      font-weight: 400;
    }

    /deep/ .van-cell__value {
      font-size: 17px;
      font-weight: 400;
    }
  }

  /deep/ .van-action-sheet__name {
    font-size: 20px;
  }

  /deep/ .van-picker-column__item {
    font-size: 20px;
  }

  /deep/ .van-picker__confirm {
    font-size: 20px;
  }

  /deep/ .van-picker__cancel {
    font-size: 20px;
  }

  /deep/ .van-ellipsis {
    font-size: 20px;
  }

  .footer {
    display: flex;
    justify-content: center;
    margin-top: 30px;

    .size {
      width: 141px;
      height: 38px;
      //opacity: 1;
      border-radius: 19px;
      background: rgba(242, 150, 0, 1);
      font-size: 23px;
      font-weight: 500;
      //line-height: 38px;
      color: rgba(255, 255, 255, 1);
      //text-align: center;
      //vertical-align: top;
      display: flex;
      justify-content: center;
      align-items: center;
      border-color: rgba(242, 150, 0, 1);
    }
  }
}
</style>
